package Controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import message.MessageSend;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import DAO.BranchDao;
import DAO.CourierDao;
import DAO.ExpressDao;
import DAO.MessageResponseDao;
import DAO.ParcelDao;
import DAO.TerminalDao;
import DAO.UserDao;
import POJO.Courier;
import POJO.Express;
import POJO.MessageResponse;
import POJO.Parcel;
import POJO.Terminal;
import POJO.User;
import Utils.ValidationHelper;

@Controller
@RequestMapping(value = "utils")
public class UtilsController {
	
	static Logger logger = Logger.getLogger(UtilsController.class);
	@Autowired
	BranchDao branchDao;
	@Autowired
	UserDao userDao;
	@Autowired
	ParcelDao parcelDao;
	@Autowired
	TerminalDao terminalDao;
	@Autowired
	MessageResponseDao messageResponseDao;
	@Autowired
	CourierDao courierDao;
	@Autowired
	ExpressDao expressDao;
	
	
	@RequestMapping("timestamp")
	@ResponseBody
	public Map<String,String> returnTimeStamp(){
		HashMap<String, String> response = new HashMap<String, String>();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy.MM.dd-HH:mm:ss");
		Date date=new Date();
		response.put("result", "0");
		response.put("timestamp", sdf.format(date));
		return response;
	}
	/**
	 * 通过JSONP方式给YouBoxAd使用
	 * @param response
	 * @param callback
	 * @throws Exception
	 */
	@RequestMapping("branches")
	public void returnBanches(HttpServletResponse response,
				@RequestParam("callback")String callback) throws Exception{
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		JSONArray jsonArray=JSONArray.fromObject(branchDao.getAll());
		JSONObject jsonObj= new JSONObject();
		jsonObj.put("branches", jsonArray.toString());
		response.getWriter().write(callback + "(" + jsonObj.toString() + ")");
	}
	
	
	@RequestMapping("isUserRegistered")
	@ResponseBody
	public Map<String,String> isUserRegistered(@RequestParam("phoneNum")String phoneNum){
		HashMap<String, String> response = new HashMap<String, String>();
		if(!userDao.isRFIDNull(phoneNum)){
			response.put("result", "0");
		}else{
			response.put("result", "1");
		}
		return response;
	}
	/**
	 * 用户注册，如果用户手机号已经存在，则更新RFID,否则直接新增记录
	 * @param phoneNum
	 * @param rfid
	 * @return
	 */
	@RequestMapping("RegisterUser")
	@ResponseBody
	public Map<String, String> RegisterUser(
			@RequestParam("phoneNum") String phoneNum,
			@RequestParam("rfid") String rfid,
			HttpSession httpSession) {

		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal =(Terminal)httpSession.getAttribute("terminal");
		if(terminal!=null){
			User user = new User();
			user.setRFID(rfid);
			user.setMobileNum(phoneNum);
			if (userDao.isRFIDRegister(rfid)) {
				response.put("result", "2");
			} else {
				if(userDao.isUserExisted(phoneNum)){
					if (userDao.updateRFID(phoneNum,rfid,terminal)) {
						response.put("result", "0");
					} else {
						response.put("result", "1");
					}
				}else{
					if (userDao.saveUserInfo(user,terminal)!=0) {
						response.put("result", "0");
					} else {
						response.put("result", "1");
					}
				}
			}
		}else{
			response.put("result", "9");
		}

		return response;
	}
	
	@RequestMapping("isUserRegister")
	@ResponseBody
	public Map<String,Object> isRegister(@RequestParam("phoneNum")String phoneNum){
		HashMap<String,Object> response=new HashMap<String,Object>();
		boolean result=userDao.isUserRegister(phoneNum);
		if(result){
			response.put("result", "0");
		}else{
			response.put("result", "1");
		}
		return response;
		
	}
	
	@RequestMapping("ConfWrite")
	@ResponseBody
	public Map<String,String> ConfWrite(@RequestParam("ip")String ip,
									    @RequestParam("addr")String addr,
									    @RequestParam("port")String port,
									    @RequestParam("ftpname")String ftpname,
									    @RequestParam("ftppwd")String ftppwd,
									    @RequestParam("savePath")String savePath,
									    @RequestParam("terminalId")String terminalId,
									    HttpServletRequest httpRequest){
		HashMap<String, String> response = new HashMap<String, String>();
		
		HashMap<String, Object> responseData = new HashMap<String, Object>();
			HashMap<String, String> downloadParam = new HashMap<String, String>();
			downloadParam.put("ip", ip);
			downloadParam.put("addr", addr);
			downloadParam.put("port", port);
			downloadParam.put("ftpname", ftpname);
			downloadParam.put("ftppwd", ftppwd);
			downloadParam.put("savePath", savePath);
		responseData.put("result", "2");
		responseData.put("downloadParam", downloadParam);
		httpRequest.getServletContext().setAttribute("terminal"+terminalId, responseData);
//		logger.info("write info");
		response.put("result", "0");
		return response;
		
	}
	
	
	
	
	
	

	@RequestMapping("statusWrite")
	@ResponseBody
	public Map<String,String> statusWrite(@RequestParam("terminalId")String terminalId,
										  @RequestParam("status")String status,
										  @RequestParam(value="serverIP",required=false)String serverIP,
										  @RequestParam(value="portNum",required=false)String portNum,
										  HttpServletRequest httpRequest){
		HashMap<String, String> response = new HashMap<String, String>();
		HashMap<String, Object> responseData = new HashMap<String, Object>();
//		logger.info("write status");
		responseData.put("result", status);
		//reverse SSH
		if(status.equals("6")){
			responseData.put("serverIP", serverIP);
			responseData.put("portNum", portNum);
		}
		httpRequest.getServletContext().setAttribute("terminal"+terminalId, responseData);
		response.put("result", "0");
		return response;
		
	}
	
	/**
	 * 根据单号获取收件人的号码
	 * @param parcelNum
	 * @return
	 */
	@RequestMapping("parcelSeqReturnMobileNum")
	@ResponseBody
	public Map<String,String> parcelSeqReturnMobileNum(@RequestParam("parcelNum")String parcelNum){
		HashMap<String, String> response = new HashMap<String, String>();
		String phoneNum=parcelDao.getMobileNumByParcelNum(parcelNum);
		if(phoneNum!=null){
			if(ValidationHelper.isMobileNum(phoneNum)){
				response.put("result", "0");
				response.put("phoneNum", phoneNum);
			}else{
				logger.info("[ERROR] wrong mobile phone format");
				response.put("result", "1");
			}
		}else{
			response.put("result", "1");
		}
		return response;
	}
	
	/**
	 * 清除掉缓存内的checkCode,修复后台“清空”操作带来的bug
	 * @param terminalId
	 * @param checkCode
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("cleanCheckCode")
	@ResponseBody
	public Map<String,String> cleanCheckCodeInCache(@RequestParam("terminalId")String terminalId,
													@RequestParam("checkCode")String checkCode,
													HttpServletRequest httpRequest){
		HashMap<String, String> response = new HashMap<String, String>();
		if(httpRequest.getServletContext().getAttribute(terminalId+checkCode)!=null){
			httpRequest.getServletContext().removeAttribute(terminalId+checkCode);
			response.put("result", "0");
		}else{
			response.put("result","1");
		}
		return response;
	}
	
	@RequestMapping("updateTerminalInfoInCache")
	@ResponseBody
	public Map<String,String> updateTerminalInfoInCache(@RequestParam("terminalId")int terminalId,
														HttpServletRequest httpRequest){
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal=terminalDao.get(terminalId);
		System.out.println("update:");
		if(terminal!=null){
			httpRequest.getServletContext().setAttribute("terminalCache"+terminal.getTerminalID()+terminal.getPassword(), terminal);
			response.put("result","0");
		}else{
			response.put("result","1");
			logger.error("更新终端缓存失败，没有指定的终端号");
		}
		return response;
		
	}
	
	/**
	 * 在管理后台执行修改终端密码时，请务必先执行此方法
	 * @param terminalId
	 * @param httpRequest
	 * @return
	 */
	@RequestMapping("removeTerminalCache")
	@ResponseBody
	public Map<String,String> removeTerminalCache(@RequestParam("terminalId")int terminalId,
														HttpServletRequest httpRequest){
		HashMap<String, String> response = new HashMap<String, String>();
		Terminal terminal=terminalDao.get(terminalId);
		Terminal terminalCache=(Terminal) httpRequest.getServletContext().getAttribute("terminalCache"+terminal.getTerminalID()+terminal.getPassword());
		if(terminal!=null&&terminalCache!=null){
			httpRequest.getServletContext().removeAttribute("terminalCache"+terminal.getTerminalID()+terminal.getPassword());
			response.put("result","0");
		}else{
			response.put("result","1");
			logger.error("清除终端缓存失败，没有指定的终端号");
		}
		return response;
	}
	
	/**
	 * 接受短信网关发送，更新短信状态
	 * @param phone
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("messageStatusReport")
	@ResponseBody
	public int messageStatusReport(@RequestParam("phone")String phone) throws IOException{
		String ReportStr=URLDecoder.decode(phone,"GBK");
		String[] msgs=ReportStr.split(";");
		if(msgs.length>0){
			for(String msg:msgs){
				String[] statusEntity=msg.split(",");
				int resultSMSState=Integer.parseInt(statusEntity[2]);
				MessageResponse messageResponse=new MessageResponse();
				messageResponse.setMessageId(Long.parseLong(statusEntity[0]));
				if(resultSMSState==1){
					//success
					messageResponse.setStatus(1);
				}else if(resultSMSState<0){
					//fail
					messageResponse.setStatus(-1);
				}else if(resultSMSState==0){
					//unknown
					messageResponse.setStatus(0);
				}
				messageResponseDao.updateMessageResposne(messageResponse);
			}
			
		}
		return 0;
	}
	
	/**
	 * 取件通知短信重发端口
	 * @param parcelId
	 * @return
	 */
	@RequestMapping("resendParcelMessage")
	@ResponseBody
	public Map<String,String> resendParcelMessage(@RequestParam("parcelId")int parcelId,@RequestParam(value = "endMsg", defaultValue = "-1")String endMsg){
		HashMap<String, String> response = new HashMap<String, String>();
		try {
			Parcel parcel=parcelDao.getParcelbyId(parcelId);
			Courier courier=courierDao.getCourierByID(parcel.getCourierId());//可能快递员为null报错
			Express express = expressDao.getExpressById(courier.getExpressId());
			Terminal terminal=terminalDao.get(parcel.getTerminalId());
			String msgTemplate=branchDao.getMsgTemplate(terminal.getBranchID());
			if(!"-1".equals(endMsg)){
				msgTemplate+=endMsg;
			}
			MessageSend messageSend=new MessageSend(parcel, terminal, courier,express, msgTemplate);
			MessageResponse messageResponse=messageSend.send();
			if(messageResponse.getMessageId()==-1){
				response.put("result", "1");
				return response;
			}
			int resultOfInMsgRp=messageResponseDao.InsertMessageResponse(messageResponse);
			if(resultOfInMsgRp==1){
				response.put("result", "0");
			}else{
				response.put("result", "1");
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.put("result", "1");
		}

		return response;
		
	}

	/**
	 * 处理vcomcn短信平台状态回复
	 * @param searchID
	 * @param state
	 * @return
	 */
	@RequestMapping("vcomcnResponse")
	@ResponseBody
	public int vcomcnResponse(@RequestParam("searchID")String searchID,
											@RequestParam("state")String state){
		MessageResponse messageResponse=new MessageResponse();
		if(state.equals("S0S")){
			messageResponse.setMessageId(Long.parseLong(searchID));
			messageResponse.setStatus(1);
		}else{
			messageResponse.setMessageId(Long.parseLong(searchID));
			messageResponse.setStatus(-1);
		}
		messageResponseDao.updateVcomcnMessageResposne(messageResponse);
		

		return 0;
	}
	
	/**
	 * 处理鸿联企信通短信平台状态回复
	 * @param FLinkID
	 * @return
	 */
	@RequestMapping("hl95Response")
	@ResponseBody
	public int hl95Response(@RequestParam("FLinkID")String FLinkID,
							@RequestParam("FreportCode")String FreportCode){
		MessageResponse messageResponse=new MessageResponse();
		if(FreportCode.trim().endsWith("0")){
			messageResponse.setMessageId(Long.parseLong(FLinkID));
			messageResponse.setStatus(1);
		}
		messageResponseDao.updateVcomcnMessageResposne(messageResponse);
		return 0;
	}
	
	
	
	@RequestMapping("test")
	@ResponseBody
	public Map<String,String> returnTimeStamp(@RequestParam("sign")String sign,
			@RequestParam("timestamp")String timestamp,
	@RequestParam("funcName")String funcName,
	@RequestParam("orderNo")String orderNo,
	@RequestParam("boxStatus")String boxStatus,
	@RequestParam(value="openCode",required=false)String openCode){
		HashMap<String, String> response = new HashMap<String, String>();
		response.put("result", "0");
		response.put("sign", sign);
		response.put("funcName", funcName);
		response.put("boxStatus", boxStatus);
		response.put("openCode", openCode);
		response.put("timestamp", timestamp);
		response.put("orderNo", orderNo);
		return response;
	}
}
